/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package core;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.TSFile;

/**
 *
 * @author Flavio
 */
class SenderThread extends Thread{

    private PoolThreads pool;

    public SenderThread(PoolThreads p){
        pool = p;
    }

    @Override
    public void run(){
        TuppleSender s;
        while(true){
            LinkedList<TuppleSender> queue = pool.getQueueSender();
            System.out.println("Ve se tem dados para enviar");
            synchronized(queue){
                while(queue.isEmpty()) try {
                    queue.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(SenderThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                s = queue.removeFirst();
            }
            ProtocolSD proto = s.getProtocol();
            int key = s.getKey();
            TSFile file = pool.get(key);
            if(file==null){
                synchronized(proto){
                    try {
                        file = new TSFile(key);
                        if(file.openFile()){
                            FileChannel channel = file.getReadChannel();
                            proto.write(key, channel);
                        }else {
                            System.out.println("Não conseguiu abrir o ficheiro: "+key);
                        }

                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(SenderThread.class.getName()).log(Level.SEVERE, null, ex);
                        pool.returnErrorOnSending(file);
                    } catch (IOException ex) {
                        Logger.getLogger(SenderThread.class.getName()).log(Level.SEVERE, null, ex);
                        pool.returnErrorOnSending(file);
                    }
                }
            }else {
                System.out.println("Alguém está a escrever no ficheiro");
                pool.returnErrorOnSending(file);
            }
            
        }
    }
}
